package Netty_basic;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;


//池化
public class element_Bytebuf {

    public static void main(String[] args) {
        ByteBuf byteBuf= ByteBufAllocator.DEFAULT.directBuffer(10);//使用的直接内存
        byteBuf.writeBytes(new byte[]{1,2,3,4,5});
        log(byteBuf);
        byteBuf.writeBytes("aaaaaaaaaaaaaaxacsdacdacac".getBytes());//会自动扩容
        log(byteBuf);
        ByteBuf slice = byteBuf.slice(0, 10);//零拷贝
        log(slice);
        slice.setByte(0,2);//这里改了，原始的bytebuf也会改，证明这俩bytebuf用的是同一个对象
        log(byteBuf);
    }

    private static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf.toString());
    }
}
